from django import http
from django.shortcuts import render, redirect
# Create your views here.
from django.views import View
from QQLoginTool.QQtool import OAuthQQ
from django.conf import settings
from django.contrib.auth import authenticate, login
from django_redis import get_redis_connection

from meiduo.utils.response_code import RETCODE
from oauth.models import OAuthQQUser
from oauth.utils import openid_encode, openid_decode
from users.models import User

class Oauth(View):
    def get(self,request):
        next = request.GET.get('next','/')
        auth_qq = OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                          client_secret=settings.QQ_CLIENT_SECRET,
                          redirect_uri=settings.QQ_REDIRECT_URI,
                          state=next)
        login_url = auth_qq.get_qq_url()
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK', 'login_url': login_url})


class QQAuthUserView(View):
    def get(self,request):
        code = request.GET.get("code",None)
        auth_qq = OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                          client_secret=settings.QQ_CLIENT_SECRET,
                          redirect_uri=settings.QQ_REDIRECT_URI,
                          )
        token = auth_qq.get_access_token(code=code)

        openid = auth_qq.get_open_id(access_token=token)
        #如果认证成功我们需要到数据库中提取数据
        try:
            user_opid =OAuthQQUser.objects.get(openid=openid)
        except:
            openid = openid_encode(openid)

            return render(request,'oauth_callback.html',{"openid":openid})
            # 用户之前没有绑定过
        else:
            user = user_opid.user
            next = request.GET.get("next",'/')
            #用户之前绑定过
            response = redirect(next)
            login(request,user)
            response.set_cookie("username",user.username,max_age=settings.SESSION_COOKIE_AGE)
            return response

    def post(self,request):
        query_dict = request.POST
        password = query_dict.get("password")
        mobile = query_dict.get("mobile")
        openid = query_dict.get("openid")
        sms_code= query_dict.get("sms_code")
        conn = get_redis_connection('SMSCODE')
        # TODO all 能够判断列表里面的数据有没有值,只有都有值才会返回True
        if all([password,mobile,openid,sms_code]) is False:
            return http.HttpResponseForbidden('缺少必传参数')
        # 确认必传数据都有的话，对比验证码是否正确
        sms_code2 = conn.get(mobile).decode()
        if sms_code!=sms_code2:
            return http.JsonResponse({'code': RETCODE.SMSCODERR, 'errmsg': '短信验证码输入错误'})

        try:
            user = User.objects.get(mobile=mobile)
        except:
            #这里就是没有查询到的用户
            return render(request,'register.html')
        else:
            user_bool = authenticate(username=mobile, password=password)
            if user_bool is not None:
                # 绑定用户
                parse_openid = openid_decode(openid)
                OAuthQQUser.objects.create(user=user,openid=parse_openid)
            else:
                # 查询到用户，但是密码账户不正确
                return render(request, 'oauth_callback.html', {"openid": openid})
            login(request, user)
            response = redirect(request.GET.get('state') or '/')
            response.set_cookie('username', user.username, max_age=settings.SESSION_COOKIE_AGE)
            return response
        # 如果没有查到则要创建新用户